package Semaphore_8;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class tryAcquire_有限等待资源 {
    public static void main(String[] args) {
        final int THREAD_COUNT = 15;
        final Semaphore semaphore = new Semaphore(2); // 只允许2个线程同时访问

        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        System.out.println("线程-" + threadId + " 尝试获取许可(最多等待1秒)");
                        if (semaphore.tryAcquire(1, TimeUnit.SECONDS)) {
                            try {
                                System.out.println("线程-" + threadId + " 获得许可，开始工作");
                                Thread.sleep(1500); // 模拟工作耗时
                                System.out.println("线程-" + threadId + " 工作完成");
                            } finally {
                                semaphore.release();
                            }
                        } else {
                            System.out.println("线程-" + threadId + " 获取许可超时，放弃操作");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}